import useConversationStore from '@/store/conversation';
import useMessageStore from '@/store/message';
import type { ExMessageItem } from '@/store/message';
import emitter from '@/utils/events';
import { IMSDK, IMMethods } from '@/utils/im';
import type { MessageItem, SendMsgParams } from '@openim/client-sdk';
import { MessageStatus } from '@openim/client-sdk';

const messageStore = useMessageStore();
const conversationStore = useConversationStore();

type SendMessageParams = Partial<Omit<SendMsgParams, 'message'>> & {
  message: MessageItem;
  needOpreateMessage?: boolean;
};

export default function useSendMessage() {
  const sendMessage = async ({
    recvID,
    groupID,
    message,
    needOpreateMessage,
  }: SendMessageParams) => {
    needOpreateMessage = needOpreateMessage ?? inCurrentConversation(recvID || groupID);

    if (needOpreateMessage) {
      messageStore.pushNewMessage(message);
      emitter.emit('CHAT_MAIN_SCROLL_TO_BOTTOM', false);
    }

    const options = {
      recvID: recvID ?? conversationStore.storeCurrentConversation.userID ?? '',
      groupID: groupID ?? conversationStore.storeCurrentConversation.groupID ?? '',
      message,
    };
    try {
      const { data: successMessage } = await IMSDK.asyncApi(
        IMMethods.SendMessage,
        IMSDK.uuid(),
        options
      );
      messageStore.updateOneMessage(successMessage as ExMessageItem, true);
    } catch (error) {
      console.error(error);

      messageStore.updateOneMessage({
        ...message,
        status: MessageStatus.Failed,
      });
    }
  };

  const inCurrentConversation = (sourceID?: string) =>
    sourceID
      ? conversationStore.storeCurrentConversation.userID === sourceID ||
        conversationStore.storeCurrentConversation.groupID === sourceID
      : true;

  return {
    sendMessage,
  };
}
